package com.dong.router.api.model

import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import java.lang.Exception

/**
 * @description:
 * @author dong
 * @date 2022/2/25 17:25
 */
class Postcard(activityName: String) {

    private val mActivityName: String = activityName
    private var mBundle: Bundle

    init {
        mBundle = Bundle()
    }

    fun withString(key: String?, value: String?): Postcard {
        mBundle.putString(key, value)
        return this
    }

    fun withInt(key: String?, value: Int): Postcard {
        mBundle.putInt(key, value)
        return this
    }

    fun withFloat(key: String?, value: Float): Postcard {
        mBundle.putFloat(key, value)
        return this
    }

    fun withLong(key: String?, value: Long): Postcard {
        mBundle.putLong(key, value)
        return this
    }

    fun withParcelable(key: String?, value: Parcelable?): Postcard {
        mBundle.putParcelable(key, value)
        return this
    }

    fun with(bundle: Bundle?): Postcard {
        if (null != bundle) {
            mBundle = bundle
        }
        return this
    }

    fun navigation(context: Context) {
        if(mActivityName.isNullOrBlank()) return
        try {
            val intent = Intent()
            intent.component = ComponentName(context.packageName, mActivityName)
            intent.putExtras(mBundle)
            if (context !is Activity) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            context.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun navigation(context: Activity, requestCode: Int) {
        if(mActivityName.isNullOrBlank()) return
        try {
            val intent = Intent()
            intent.component = ComponentName(context.packageName, mActivityName)
            intent.putExtras(mBundle)
            context.startActivityForResult(intent, requestCode)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}